package com.fh.controller.system.websocket;


import com.fh.controller.base.BaseController;
import net.sf.json.JSONObject;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.net.URLDecoder;
import java.util.*;


/**
 * 广播消息
 *
 */
@ServerEndpoint("/GroupChat")
public class ChatSocket extends BaseController {

    //存所有的通道连接
    private static List<Session> conlist = new ArrayList<Session>();
    //存所有连接者的用户ID
    private static List<String> nameList = new ArrayList<String>();
    //连接者的ID和session的对应关系
    private static Map<Session,String> userMap = new HashMap<Session,String>();
    //socket的Session
    private Session session;
    //连接者ID
    private String name;


    /**
     * @param session
     * 建立通道连接
     */
    @OnOpen
    public void open(Session session,EndpointConfig config){
        conlist.add(session);
        this.name = session.getQueryString().split("=")[1];
        try {
            this.name = URLDecoder.decode(this.name,"UTF-8");
            System.out.println(this.name);
            nameList.add(this.name);
            userMap.put(session, this.name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("通道建立:name="+name+" , session="+session.getId());
    }

    /**
     * @param session
     * @param msg
     * 接收消息处理
     */
    @OnMessage
    public void message(Session session,String msg) throws Exception{
        JSONObject json = JSONObject.fromObject(msg);
        String nameTage = json.get("nameTage").toString();
        Thread.sleep(1000);
        if(!conlist.isEmpty()){
            Iterator<Session> it = conlist.iterator();
            while(it.hasNext()){
                Session s = (Session) it.next();
                String name = userMap.get(s);
                if(name.equals(nameTage)){
                    s.getBasicRemote().sendText(msg);
                }
            }
        }


    }



    /**
     * @param t
     * @param session
     * 出错处理
     */
    @OnError
    public void error(Throwable t,Session session){
        System.out.println("websocket通讯异常请重新建立连接");
    }

    /**
     * @param session
     * 通道关闭处理
     */
    @OnClose
    public void close(Session session){
        conlist.remove(session);
        String name = userMap.get(session);
        nameList.remove(name);
        userMap.remove(session);
    }

    /**
     * 广播消息
     */
    public void broadcast(String name) throws Exception{



    }



}
